package com.ruoyi.wechat.utils;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.wechat.config.WechatConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class WechatLoginUtil {
    @Autowired
    private WechatConfig wechatConfig;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 通过code获取微信openid和session_key
     * @param code 小程序wx.login()获取的code
     * @return 包含openid和session_key的JSON对象
     */
    public JSONObject getOpenidAndSessionKey(String code) {
        // 拼接请求URL
        String url = String.format("%s?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                wechatConfig.getLoginUrl(),
                wechatConfig.getAppId(),
                wechatConfig.getAppSecret(),
                code);

        // 发送GET请求
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

        // 解析响应结果
        if (response.getStatusCode().is2xxSuccessful()) {
            return JSONObject.parseObject(response.getBody());
        }
        throw new RuntimeException("调用微信登录接口失败");
    }
}